package com.rh.file.controller;

import com.rh.entity.file.RenHaiFile;
import com.rh.file.service.FileService;
import com.rh.file.service.RenHaiFileService;
import com.rh.file.util.FileUpload;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import renhai.util.ResponseContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping(value = "/api/file/file")
public class FileController {

    private final FileService service;
    private final RenHaiFileService renHaiFileService;


    public FileController(FileService service, RenHaiFileService renHaiFileService) {
        this.service = service;
        this.renHaiFileService = renHaiFileService;
    }

    @ApiOperation("大文件分片上传检查")
    @GetMapping("chunkUpload")
    public ResponseContext fileChunkUpload(FileParam param) {
        RenHaiFile file = renHaiFileService.checkUploading(param);
        return new ResponseContext<>(file, "GET");
    }

    @ApiOperation("大文件分片上传")
    @PostMapping("chunkUpload")
    public ResponseContext fileChunkUpload(FileParam param, HttpServletResponse response, HttpServletRequest request) {
        /**
         * 判断前端Form表单格式是否支持文件上传
         */
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            return new ResponseContext<>(param, 0, "没有文件");
        }
        boolean flag = false;
        try {
            flag = service.chunkUploadByMappedByteBuffer(param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        param.setFile(null);
        if (flag) {
            return new ResponseContext<>(renHaiFileService.getById(param.getTaskId()), 1, "上传成功");
        } else {
            return new ResponseContext<>(param, 0, "正在上传");
        }
    }
}